<template>
    <div class="container">
        <h3>单位管理</h3>
        <el-form ref="form" label-width="120px" style="margin-top:20px;">
            <el-form-item v-for="(item,index) in unit" :key="index+'00'" label="单位：">
                <el-input v-model="item.name" style="width:200px;" disabled></el-input>
            </el-form-item>

            <el-form-item v-for="(item,index) in units" :key="index+'01'" label="单位：">
                <el-input v-model="item.name" style="width:200px;" :disabled="disabled"
                          @input="accountInput"></el-input>
                <el-button @click="deleteUnit(index)" v-if="!edit" class="delete_btn">删除</el-button>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="unit_save" class="unit_save">保存</el-button>
                <el-button v-if="!addeds" @click="added_unit" class='added_unit'>添加一条</el-button>
            </el-form-item>
            <el-form-item class="footerFixed" v-if="goback">
                <!-- <el-button type="primary" @click="submitRules('ruleForm')">提交</el-button> -->
                <el-button @click="backPage">返回</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
    import {unit_findByList, unit_save, unit_delete} from "@/request/api"
    export default {
        name: 'unit',
        components: {},
        data() {
            return {
                unit: [],
                disabled: false,
                goback: false,
                type: '',
                units: [],
                addeds:true,
                edit: true,
                date: []
            };
        },
        mounted () {
            this.type = this.$route.query.type
            if (this.type == "added") {
                this.goback = true
            } else {
                this.goback = false
            }
            this.init();
            this.judgmentAuthority();
        },
        created(){

        },
        methods: {
            accountInput(val){

            },
            // changeCode(index){

            //     this.$nextTick(() => {
            //         console.log(index)
            //         if(this.units[index].name !== null){
            //             this.units[index].name = this.units[index].name.replace(/[^\w\.\/]/ig,'')
            //             console.log(this.units[index].name)
            //         }
            //     })
            // },
            backPage(){
                this.$router.go(-1)
            },
            init(){
                unit_findByList("").then((res) => {
                    this.unit = [];
                    this.units = [];
                    if (res.data.length > 0) {
                        for (var i = 0; i < res.data.length; i++) {
                            if (res.data[i].name == 'kg' || res.data[i].name == 'g') {
                                this.unit.push(res.data[i])
                            } else {
                                this.units.push(res.data[i])
                            }
                        }
                    }
                    if (this.unit.length == 0) {
                        this.unit = [{name: 'kg'}, {name: 'g'}];
                        unit_save(this.unit).then((res) => {
                            this.init();
                        })
                    }
                })
            },
            // 删除 单位
            deleteUnit(index){
                var id = this.units[index].id
                this.$confirm('是否确定删除该单位?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if (id == undefined) {
                        this.units.splice(index, 1)
                        this.$notify({
                            title: '提示',
                            message: '删除成功',
                            type: 'success',
                            duration: 500
                        });
                    } else {
                        unit_delete(id).then((res) => {
                            this.units.splice(index, 1)
                            this.$notify({
                                title: '提示',
                                message: '删除成功',
                                type: 'success',
                                duration: 1000
                            });
                        })
                    }
                }).catch(() => {
//                     this.$notify({
//                         title: '提示',
//                         message: '已取消删除',
//                         type: 'info',
//                         duration:500
//                     });
                });

            },

            //保存
            unit_save(){
                this.$confirm('是否确定提交?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'

                }).then(() => {
                    this.date=[];
                    if (this.unit.length > 0) {
                        for (let i = 0; i < this.unit.length; i++) {
                            this.date.push(this.unit[i]);
                        }
                    }
                    if (this.units.length > 0) {
                        for (let i = 0; i < this.units.length; i++) {
                            this.date.push(this.units[i]);
                        }
                    }
                    for (let i = 0; i < this.date.length; i++) {
                        for (let j = i + 1; j < this.date.length; j++) {
                            if (this.date[i].name == this.date[j].name) {
                                var tishi = '单位不能重复'
                                this.$notify({
                                    title: '提示',
                                    message: tishi,
                                    type: 'info',
                                    duration: 1000
                                });
                                return false
                            }
                        }
                    }
                    for (let i = 0; i < this.date.length; i++) {
                        if (this.date[i].name == "") {
                            var tishi = '单位不能为空'
                            this.$notify({
                                title: '提示',
                                message: tishi,
                                type: 'info',
                                duration: 1000
                            });
                            return false
                        }
                    }
                    unit_save(this.date).then((res) => {
                        this.$notify({
                            title: '提示',
                            message: '保存成功',
                            type: 'success',
                            duration: 500
                        });
                        this.init();
                    })
                }).catch(() => {
                    this.$notify({
                        title: '提示',
                        message: '已取消保存',
                        type: 'info',
                        duration: 500
                    });
                });
            },
            //添加单位
            added_unit(){
                let unit = {
                    name: ''
                };
                this.units.push(unit);
            },

            //判定操作按钮显示
            judgmentAuthority() {
                var type = JSON.parse(localStorage.getItem('userInfo')).appMenus;
                var URL = localStorage.getItem('requestUrl');
                type.map((item) => {
                    if (item.appName == '种植平台' && URL == item.appUrl) {
                        item.menus.map((item1) => {
                            if (item1.name == '常用单位' && item1.children != null) {
                                for (var i = 0; i < item1.children.length; i++) {
                                    if (item1.children[i].name == '新增') this.addeds = false;
                                    if (item1.children[i].name == '删除') this.edit = false;
                                }
                            }
                        });
                    }
                    if (item.appName == '养殖追溯管理系统' && URL == item.appUrl) {
                        item.menus.map((item1) => {
                            if (item1.name == '常用单位' && item1.children != null) {
                                for (var i = 0; i < item1.children.length; i++) {
                                    if (item1.children[i].name == '新增') this.addeds = false;
                                    if (item1.children[i].name == '删除') this.edit = false;
                                }
                            }
                        });
                    }
                });
            }
        },

        watch: {},
    };
</script>


<style scoped>
    .container {
        min-height: 65%;
    }

    .delete_btn {
        margin-left: 6px;
    }
</style>
